/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kpi.dss.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import kpi.dss.TimeSeries;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author harker777
 */
public class TimeSeriesImporter {

	public static ArrayList<TimeSeries> loadTimeSeries(File file) throws FileNotFoundException {
		FileInputStream stream = new FileInputStream(file);
		return loadTimeSeriesFromStream(stream);
	}

	private static ArrayList<TimeSeries> loadTimeSeriesFromStream(FileInputStream stream) {
		try {
			Workbook workbook = new XSSFWorkbook(stream);
			return loadTimeSeriesFromWorkbook(workbook);
		} catch (IOException ex) {
			Logger.getLogger(TimeSeriesImporter.class.getName()).log(Level.SEVERE, null, ex);
		}
		return null;
	}

	private static ArrayList<TimeSeries> loadTimeSeriesFromWorkbook(Workbook workbook) {
		ArrayList<TimeSeries> result = new ArrayList<>();

		ArrayList<Sheet> sheets = new ArrayList<>();
		for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
			sheets.add(workbook.getSheetAt(sheetNum));
		}

		for (Sheet sheet : sheets) {
			result.addAll(loadTimeSeriesFromSheet(sheet));
		}

		return result;
	}

	private static ArrayList<TimeSeries> loadTimeSeriesFromSheet(Sheet sheet) {
		ArrayList<TimeSeries> result = new ArrayList<>();

		int firstRowNum = sheet.getFirstRowNum();
		int lastRowNum = sheet.getLastRowNum();

		Row firstRow = sheet.getRow(firstRowNum);

		for (int columnNum = 0; firstRow.getCell(columnNum) != null; columnNum++) {
			String seriesName = firstRow.getCell(columnNum).toString();
			TimeSeries series = new TimeSeries(seriesName);

			for (int rowNum = firstRowNum + 1; rowNum < lastRowNum; rowNum++) {
				Row row = sheet.getRow(rowNum);
				String string = row.getCell(columnNum).toString();
				series.getData().add(Double.valueOf(string));
			}

			result.add(series);
		}

		return result;
	}
}
